#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import ssl
import urllib3
import requests
from pathlib import Path

# 禁用 SSL 验证
ssl._create_default_https_context = ssl._create_unverified_context
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

def download_xtts_model():
    """手动下载 XTTS v2 模型"""
    
    # 模型目录
    model_dir = Path.home() / "AppData" / "Local" / "tts" / "tts_models--multilingual--multi-dataset--xtts_v2"
    model_dir.mkdir(parents=True, exist_ok=True)
    
    print(f"模型将下载到: {model_dir}")
    
    # 模型文件列表
    model_files = [
        {
            "url": "https://coqui.gateway.scarf.sh/hf-coqui/XTTS-v2/main/model.pth",
            "filename": "model.pth"
        },
        {
            "url": "https://coqui.gateway.scarf.sh/hf-coqui/XTTS-v2/main/config.json",
            "filename": "config.json"
        },
        {
            "url": "https://coqui.gateway.scarf.sh/hf-coqui/XTTS-v2/main/speaker_encoders.pth",
            "filename": "speaker_encoders.pth"
        },
        {
            "url": "https://coqui.gateway.scarf.sh/hf-coqui/XTTS-v2/main/vocab.json",
            "filename": "vocab.json"
        }
    ]
    
    # 创建 requests session，禁用 SSL 验证
    session = requests.Session()
    session.verify = False
    
    for file_info in model_files:
        url = file_info["url"]
        filename = file_info["filename"]
        file_path = model_dir / filename
        
        print(f"\n正在下载: {filename}")
        print(f"URL: {url}")
        
        try:
            response = session.get(url, stream=True, timeout=30)
            response.raise_for_status()
            
            total_size = int(response.headers.get('content-length', 0))
            downloaded = 0
            
            with open(file_path, 'wb') as f:
                for chunk in response.iter_content(chunk_size=8192):
                    if chunk:
                        f.write(chunk)
                        downloaded += len(chunk)
                        if total_size > 0:
                            percent = (downloaded / total_size) * 100
                            print(f"\r进度: {percent:.1f}% ({downloaded}/{total_size} bytes)", end='')
            
            print(f"\n✓ {filename} 下载完成")
            
        except Exception as e:
            print(f"\n✗ {filename} 下载失败: {e}")
            return False
    
    print(f"\n所有文件下载完成！模型目录: {model_dir}")
    return True

if __name__ == "__main__":
    print("开始下载 XTTS v2 模型...")
    success = download_xtts_model()
    if success:
        print("模型下载成功！")
    else:
        print("模型下载失败！")

